﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using SpringStudio.Common;
using SpringStudio.DAL;
using Sdepci.InfoCode.BLL.Authority;

namespace Sdepci.InfoCode.Web
{
    public partial class Contents : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this.BindData();
            }
        }

        private void BindData()
        {
            XmlDocument xmldoc = new FunctionManager().GetFunctionXmlDoc();  // 获取全部菜单
            XmlNode root = xmldoc.GetElementsByTagName("root")[0];
            // 递归剔除掉所有没有权限的菜单项
            if (Session["User"] != null)
            {
                string functionGuids = string.Empty;
                if ((Session["User"] as User).RoleGuid != "")
                {
                    functionGuids = new Role((Session["User"] as User).RoleGuid).FuncGuids;
                }
                else
                {
                    functionGuids = new RoleManager().GetDefaultRole().FuncGuids;
                }
                this.RemoveFunctions(ref root, functionGuids);
            }

            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script language=\"javascript\">document.getElementById(\"TreeXmlData\").value = '" + root.OuterXml + "';</script>");
        }

        /// <summary>
        /// 递归剔除掉所有没有权限的菜单项
        /// </summary>
        /// <param name="xmldoc"></param>
        /// <param name="parent"></param>
        /// <param name="functionGuids"></param>
        private void RemoveFunctions(ref XmlNode parent, string functionGuids)
        {
            if (parent.HasChildNodes)
            {
                for (int i = 0; i < parent.ChildNodes.Count; i++)
                {
                    XmlNode node = parent.ChildNodes[i];

                    if (functionGuids.IndexOf(node.Attributes["id"].Value) > -1)
                    {
                        this.RemoveFunctions(ref node, functionGuids);
                    }
                    else
                    {
                        parent.RemoveChild(node);
                        i--;
                    }
                }
            }
        }
    }
}
